<template>
  <!-- 用户名密码登录 -->
  <div class="loginFormStyle">
    <el-form
      label-position="top"
      :rules="state.rules"
      :model="state.ruleForm"
      ref="loginForm"
    >
      <el-form-item label="" prop="username" style="margin-bottom: 50px">
        <el-input
          type="text"
          v-model.trim="state.ruleForm.username"
          placeholder="请输入用户名"
        >
          <template #prefix>
            <img
              style="width: 23px; height: 23px"
              src="@/assets/iconImg/user.png"
              alt=""
            />
            <el-divider
              direction="vertical"
              style="height: 30px; border-left: 1px solid #e3e7f1"
            />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="" prop="password" style="margin-bottom: 70px">
        <el-input
          type="password"
          v-model.trim="state.ruleForm.password"
          placeholder="请输入密码"
          @keyup.enter="submitForm"
          show-password
        >
          <template #prefix>
            <img
              style="width: 23px; height: 23px"
              src="@/assets/iconImg/password.png"
              alt=""
            />
            <el-divider
              direction="vertical"
              style="height: 30px; border-left: 1px solid #e3e7f1"
            />
          </template>
        </el-input>
        <div class="forgetBtn" @click="forgetPassword">忘记密码？</div>
      </el-form-item>

      <!-- 滑块 -->
      <el-form-item label="" prop="sliderValue" style="margin-bottom: 66px">
        <el-slider
          class="slider"
          v-model.trim="state.ruleForm.sliderValue"
          :show-tooltip="false"
          @change="sliderChange"
        />
      </el-form-item>
    </el-form>

    <el-dialog
      title="系统提示"
      v-model="state.dialogVisible"
      width="492px"
      top="19%"
      center
      :show-close="false"
      :close-on-click-modal="false"
    >
      <div class="dialogInfoBox">
        <el-icon
          color="#FF7B50"
          size="18px"
          style="vertical-align: middle; margin-top: -4px"
          ><WarningFilled
        /></el-icon>
        请联系管理员协助重置账号密码
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button style="width: 68px; height: 31px" @click="closeDialog"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {onMounted, reactive, ref} from "vue";
import {
    ElForm,
    ElFormItem,
    ElSlider,
    ElDialog,
    ElMessage, ElMessageBox,
} from "element-plus";
import { WarningFilled } from "@element-plus/icons-vue";
import { useStore } from "vuex";
import {useRouter} from "vue-router";
// import MD5 from 'js-md5'
import loginApi, {otherApi} from "@/api/login";
import {extractTree, filterAsyncRouter, getRootRoute} from "@/utils/createRoutes";
import {GetQueryValue} from "@/common/utils/GlobalUtils";

const store = useStore();
const router = useRouter();

const checkSliderVal = (rule, value, callback) => {
  if (value != 100) {
    callback(new Error("请拖动滑动条至最右侧完成验证"));
  } else {
    callback();
  }
};

const loginForm = ref(null);
const state = reactive({
  ruleForm: {
    username: "",
    password: "",
    sliderValue: 0,
  },
  dialogVisible: false,
  rules: {
    username: [
      { required: "true", message: "账户不能为空", trigger: "blur" },
      { max: 20, message: "账号不得超过20位", trigger: "change" },
    ],
    password: [
      { required: "true", message: "密码不能为空", trigger: "blur" },
      { min: 6, message: "密码至少为6位", trigger: "change" },
    ],
    sliderValue: [{ validator: checkSliderVal, trigger: ["change"] }],
  },
});

const sliderChange = (val) => {
  state.ruleForm.sliderValue = val;
};

const emits = defineEmits(['onChange']);

// 表单提交
const  submitForm = () => {
  loginForm.value.validate((vaild) => {
    if (vaild) {
      emits('onChange',true);
      let params = {
        account: state.ruleForm.username,
        password: state.ruleForm.password,
        // password: MD5(state.ruleForm.password),
      };

      loginApi.userLogin(params).then((res) => {
        const { code, data, msg } = res;
        if (code === "200") {
          emits('onChange',false);
          if(!res.data.menus || (res.data.menus && res.data.menus.length===0)){
              return  ElMessageBox.alert('此账号无菜单权限,请联系管理员!', '警告', {
                  confirmButtonText: 'OK',
                  callback: (action) => {},
              });
          }
          let list =   filterAsyncRouter(res.data.menus);
          store.commit('SetLeftMenu',JSON.parse(JSON.stringify(list)));
          list.forEach(route =>{
              router.addRoute(route);
          });
          const userId = data.userId;
          store.commit("SET_USERID", userId);
          const userName = data.userName;
          store.commit("SET_USERNAME", userName);
          const account = data.account;
          store.commit("SET_USERACCOUNT", account);
          const email = data.email;
          store.commit("SET_EMAIL", email);
          const phoneNumber = data.phoneNumber;
          store.commit("SET_PHNOE", phoneNumber);//departmentId
          const departmentName = data.departmentName;
          store.commit("SET_DEPARTMENT", departmentName);
          const departmentId = data.departmentId;
          store.commit("SET_DEPARTMENT_ID", departmentId);
          const tokenObj = data.token;
          store.commit("SET_TOKEN", tokenObj);
          ElMessage({
            message: "登录成功！",
            type: "success",
            duration: 1000,
          });

          setTimeout(()=>{
              // 获取根路由
              let path = getRootRoute(JSON.parse(JSON.stringify(res.data.menus)));
              router.push({ path: path });
          },1000);
        }else{
            emits('onChange',false);
        }
      }).catch(error => {
          emits('onChange',false);
      });
    }
  });
};
// 子组件的方法要想被父组件调用，需要通过此方式将需要被调用的方法暴露出去
defineExpose({ submitForm });

const forgetPassword = () => {
  state.dialogVisible = true;
};

const closeDialog = () => {
  state.dialogVisible = false;
};

/**
 * 不是OA跳转过来的登录就去清除一下缓存
 * token过期时的调用
 */
const checking = () => {
    let query = decodeURI(window.location.search.substring(1));
    let cookie =
        query.split("&").length === 0
            ? ""
            : query.split("&")[0].split("cookie=").length === 0
                ? ""
                : query.split("&")[0].split("cookie=")[1];
    let loginName = GetQueryValue("loginName");
    let type = GetQueryValue("type");

    if (!cookie || !loginName || !type) {
        store.commit('user_clear');
        store.commit("menu_clear");
        localStorage.clear();
    }
};

/*onMounted(()=>{
    checking();
});*/
</script>

<style lang="scss" scoped>
:deep(.slider){
  .el-slider__bar{
    background-color: #ff7b56 !important;
  }
}


.loginFormStyle {
  :deep(.el-form) {
    .el-form-item.is-error {
      .el-input {
        .el-input__wrapper {
          box-shadow: 0 0 0 1px #ef1515;
        }
      }
    }
    .el-form-item__content {
      .el-input {
        .el-input__wrapper {
          height: 52px;
          border-radius: 6px;
          background-color: #f7f7fa;
          box-shadow: 0 0 0 1px #f7f7fa;
          .el-input__inner {
            font-size: 18px;
            color: #808080;
          }
        }
        .el-input__wrapper.is-focus {
          box-shadow: 0 0 0 1px #808080;
        }
      }
      .el-form-item__error {
        font-size: 14px;
        color: #ef1515;
        top: 138%;
      }

      .el-slider__runway {
        height: 18px;
        background: #fcf3f0;
        border-radius: 15px;
        .el-slider__bar {
          border-radius: 15px;
          height: 18px;
        }
        .el-slider__button-wrapper {
          top: -9px;
          .el-slider__button {
            width: 34px;
            height: 34px;
            line-height: 32px;
            box-shadow: 0 0 3px 0 #999;
            border-color: #f7f7f7;
            font-size: 16px;
            color: #ccc;
          }
          .el-slider__button::after {
            content: "";
            width: 100%;
            height: 100%;
            display: block;
            background: no-repeat center url("@/assets/iconImg/right.png");
            background-size: 12px;
          }
        }
      }
    }
  }
  .dialogInfoBox {
    color: #1a1a1a;
    text-align: center;
  }
  .forgetBtn {
    position: absolute;
    top: 55px;
    right: 0;
    font-size: 14px;
    color: #999999;
    cursor: pointer;
  }
}
</style>
